'use strict';

const Controller = require('egg').Controller;

class HotController extends Controller {
    async edit() {
        const { ctx, app } = this
        const { id, name, sort, statr_time, end_time} = ctx.request.body
        ctx.validate({
            name: { type: 'string', required: true, desc: '关键词' },
            statr_time: { type: 'date', required: true, desc: '展示开始时间' },
            end_time: { type: 'date', required: true, desc: '结束时间' },
        })
        let list
        if (id == 0) { //创建
            
            if (await app.model.Hot.findOne({ where: { name } })) {
                ctx.throw(400,'关键词已存在')
            }
            list = await app.model.Hot.create({
                name, sort, statr_time, end_time
            })
        } else {//修改
            let oneList = await app.model.Hot.findByPk(id)
            if (!oneList) {
                ctx.throw(400,'数据不存在')
            }
            list = await oneList.update({
                name, sort, statr_time, end_time
            })
        }
        ctx.apiSuccess(list)
    }
    async list() {
        const { ctx, app } = this
        let newTime = new Date()

        // return
        let rows = await app.model.Hot.findAll({
            order: [['sort', 'ASC']]
        })
        let list = rows.filter(item => {
            if (item.statr_time < newTime && newTime < item.end_time) {
                return item
            }
        })
        ctx.apiSuccess({ list, newTime })
    }
    //删除
    async del(){
        const {ctx,app}=this
        const id=ctx.params.id
        const list=await app.model.Hot.findByPk(id)
        if(!list){
            ctx.throw(400,'数据不存在')
        }
        list.destroy()
        ctx.apiSuccess('删除成功')
    }

}

module.exports = HotController;
